<?php

require_once "access_token.php";
require_once "helper.php";

class txl_api {

	private $access_token;

	public function __construct() {
		$this -> access_token = new access_token("txl");
	}

	/**
	 * 在请求的企业微信接口后面自动附加token信息
	 */
	private function append_token($url) {
		$token = $this -> access_token -> get_access_token();

		if (strrpos($url, "?", 0) > -1) {
			return $url . "&access_token=" . $token;
		} else {
			return $url . "?access_token=" . $token;
		}
	}

	/**
	 * 创建一个新用户
	 * @param  [Array like Object] $data 用户信息
	 */
	public function create_user($data) {
		if ($data["name"] && $data["userid"] && $data["userid"] && $data["mobile"] && $data["department"]) {
			$url = 'https://qyapi.weixin.qq.com/cgi-bin/user/create';
			$ret = http_post($this -> append_token($url), $data);
			return $ret["content"];
		} else {
			return '{"errcode":-2,"errmsg":"params is missing"}';
		}
	}

	//更新用户信息
	public function update_user($data) {
		if ($data["name"] && $data["userid"] && $data["userid"] && $data["mobile"] && $data["department"]) {
			$url = 'https://qyapi.weixin.qq.com/cgi-bin/user/update';
			$ret = http_post($this -> append_token($url), $data);
			return $ret["content"];
		} else {
			return '{"errcode":-2,"errmsg":"params is missing"}';
		}
	}

	//根据用户ID删除用户信息
	public function delete_user($id = "") {
		if ($id) {
			$url = 'https://qyapi.weixin.qq.com/cgi-bin/user/delete?userid=$id';
			$ret = http_get($this -> append_token($url), $data);
			return $ret["content"];
		} else {
			return '{"errcode":-1,"errmsg":"user_id is invalid"}';
		}
	}

	//全量覆盖部门
	public function replace_party($data) {
		if ($data["media_id"]) {
			$url = 'https://qyapi.weixin.qq.com/cgi-bin/batch/replaceparty';
			$ret = http_post($this -> append_token($url), $data);
			return $ret["content"];
		} else {
			return '{"errcode":-2,"errmsg":"params is missing"}';
		}
	}

	//全量覆盖成员
	public function replace_user($data) {
		if ($data["media_id"]) {
			$url = 'https://qyapi.weixin.qq.com/cgi-bin/batch/replaceuser';
			$ret = http_post($this -> append_token($url), $data);
			return $ret["content"];
		} else {
			return '{"errcode":-2,"errmsg":"params is missing"}';
		}
	}

	//增量更新成员
	public function sync_user($data) {
		if ($data["media_id"]) {
			$url = 'https://qyapi.weixin.qq.com/cgi-bin/batch/syncuser';
			$ret = http_post($this -> append_token($url), $data);
			return $ret["content"];
		} else {
			return '{"errcode":-2,"errmsg":"params is missing"}';
		}
	}

	//查询批处理结果
	public function get_result($job_id) {
		if (!empty($job_id)) {
			$url = "https://qyapi.weixin.qq.com/cgi-bin/batch/getresult?jobid=" . $job_id;
			$ret = http_get($this -> append_token($url), $data);
			return $ret["content"];
		} else {
			return '{"errcode":-2,"errmsg":"params is missing"}';
		}
	}

}
